import {useRef, useState} from 'react';
import {useFrame} from '@react-three/fiber';
import * as THREE from 'three';
import {BaseBlock} from './BaseBlock.jsx';
import {RigidBody} from '@react-three/rapier';

const BlockSpinner = ({geometry, material, position = [0, 0, 0]}) => {

  const obstacleRef = useRef();

  const [speed] = useState(() =>
    (Math.random() + 0.2) * Math.random() > 0.5 ? 1 : -1);

  useFrame((state) => {
    const time = state.clock.getElapsedTime();

    const rotation = new THREE.Quaternion();
    rotation.setFromEuler(new THREE.Euler(0, time * speed, 0));
    obstacleRef.current.setNextKinematicRotation(rotation);
  });

  return (
    <group position={position}>
      <BaseBlock geometry={geometry} color={1} />
      <RigidBody ref={obstacleRef} type={'kinematicPosition'} position={[0, 0.3, 0]} restitution={0} friction={0}>
        <mesh
          geometry={geometry}
          material={material}
          position={[0, 0, 0]}
          scale={[3.5, 0.3, 0.3]}
          castShadow
          receiveShadow
        />
      </RigidBody>

    </group>
  );
};

export default BlockSpinner;
